package com.cnswhy.cloud.auth.controller;

import com.cnswhy.cloud.auth.service.RedisLockService;
import com.cnswhy.cloud.auth.service.ValidateCodeService;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.entity.CnswhyResponse;
import com.cnswhy.cloud.common.core.exception.CnswhyAuthException;
import com.cnswhy.cloud.common.core.exception.ValidateCodeException;
import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

@RestController
@Slf4j
public class SecurityController {
    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @GetMapping("oauth/test")
    public R<String> testOath(){
        return R.success("oath");
    }

    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }


    @DeleteMapping("signout")
    public R<Boolean> signout(HttpServletRequest request) throws CnswhyAuthException {
        String authorization = request.getHeader("Authorization");
        String token = StringUtils.replace(authorization, "bearer ", "");
        CnswhyResponse cnswhyResponse = new CnswhyResponse();
        if (!consumerTokenServices.revokeToken(token)) {
            throw new CnswhyAuthException("退出登录失败");
        }
        return R.success();
    }

    @Autowired
    private ValidateCodeService validateCodeService;
    @Autowired
    RedisLockService redisLockService;

    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
        //log.info("captcha");
        //redisLockService.foo2();
        validateCodeService.create(request, response);
    }

}
